package com.lmx.repoDomain.repository;

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiResourceRepository;

import java.util.Map;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.context.ActionContextHolder;
import com.lmx.common.util.CommonUtil;
import com.lmx.persistence.service.FoodPlanRecordService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.FoodPlanRecord;

/**
 * 老人用餐統計
 *
 * @author ytche
 * @date 2017年8月30日
 */
@JsonApiResourceRepository(value = FoodPlanRecord.class)
@Component
public class FoodPlanRecordRepository extends BaseRepository<FoodPlanRecord> {
	@Autowired
	private FoodPlanRecordService service;

	@PostConstruct
	public void init() {
		super.dslJpaService.setEntityClass(FoodPlanRecord.class);
	}

	@Override
	@JsonApiFindAll
	public Iterable<FoodPlanRecord> findAll(final QueryParams requestParams) {
		Map<String, String> filter = CommonUtil.getKeyMapByFilter(requestParams);
		Long tenantId = ActionContextHolder.getContext().getTenantId();
		if (!(filter.containsKey("diningDate") && StringUtils.isNumeric(filter.get("diningDate")))) {
			throw new BusinessException("",
										CommonConstants.CUSTOMER_FOOD_ERROR.DINING_WRONG.lable(),
										"diningDate cann't be null and must be isNumeric");
		}
		if ((!filter.containsKey("recordType"))
			|| filter.get("recordType").equals(CommonConstants.CUSTOMER_FOOD_RECORD_TYPE.WEEK.lable())) {
			return this.service.findWeakRecord(requestParams, tenantId);
		}
		if (filter.get("recordType").equals(CommonConstants.CUSTOMER_FOOD_RECORD_TYPE.DAY.lable())) {
			return this.service.findDayRecord(requestParams, tenantId);
		}
		if (filter.get("recordType").equals(CommonConstants.CUSTOMER_FOOD_RECORD_TYPE.TIME.lable())) {
			return this.service.findDayRecord(requestParams, tenantId);
		}
		return this.service.findWeakRecord(requestParams, tenantId);
	}
}
